var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mount = require('mount-routes');

var app = express();

// 初始化数据库模块
var database = require('./moduels/database')
database.initialize()

// 获取用户逻辑模块
var userService=require(path.join(process.cwd(),'/services/UserService'));

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(require('cors')());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// 初始化统一响应机制
var resextra=require('./moduels/resextra');
app.use(resextra);

app.use(express.static(path.join(__dirname, 'public')));

// 初始化 后台登录 passport 策略
admin_passport = require('./moduels/passport');
admin_passport.setup(app,userService.login);

// 设置 passport 登录入口点
app.use('/api/private/v1/login', admin_passport.login)
// 设置 passport 验证路径
app.use('/api/private/v1/*', admin_passport.tokenAuth)

var apiRouter = require('./routes/api');
app.use('/api', apiRouter);

// mount(app,path.join(process.cwd(),'/routes'),true);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
